package online.siwu.memorycards

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.View
import kotlinx.android.synthetic.main.activity_answer.*


@SuppressLint("SetTextI18n")
class AnswerActivity : AppCompatActivity() {

    var on = true
    val GD = GlobalData
    var timing = 0
    var whichCard = 1
    val handler = Handler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_answer)

        init()
//        test()      //..
    }

    private fun init() {
        btStatisticsYi.isEnabled = false
        btNextYi.setOnClickListener(oclNext)
        bt110CodeYi.setOnClickListener(oclCode)
        btStatisticsYi.setOnClickListener(oclStats)
        initTiming()
        showCard()
    }

    private fun initTiming() {
        tvTimingYi.text = "已用时 $timing 秒"
        timing++
        if (on)
            handler.postDelayed({ initTiming() }, 1000 * 1)
    }

    private fun test() {
        for (i in GD.arrAnswer.indices)          //test
            log(GD.arrAnswer[i].toString())         //test
    }

    private val oclNext = View.OnClickListener {
        GD.arrAnswer[whichCard - 1] = GD.str2Int(etCardYi.text.toString())
        whichCard++
        if (whichCard > GD.exerNum) {
            on = false
            GD.yiTime = timing                              //忆时间 放入GD
            btStatisticsYi.setTextColor(bt110CodeYi.textColors)
            btStatisticsYi.setBackgroundResource(R.drawable.button_green)
            btStatisticsYi.isEnabled = true
            etCardYi.isEnabled = false
            btNextYi.visibility = View.INVISIBLE
            test()
        } else
            showCard()

    }

    private val oclCode = View.OnClickListener {
        gotoActivity<CodeListActivity>(false)
    }

    private val oclStats = View.OnClickListener {
        gotoActivity<StatisticsActivity>()
    }

    private fun showCard() {
        etCardYi.setText("")
        tvWhichCardYi.text = "现在是第【 $whichCard 】张，共${GD.exerNum}张！"
    }


    //====================================
    private var isExit: Boolean = false

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            exitBy2Click() //调用双击退出函数
        return false
    }

    fun exitBy2Click() {
        val handler = Handler()
        if ((!isExit)) {
            isExit = true
            toast("再按一次退出APP")
            handler.postDelayed({ isExit = false }, 1000 * 2) //x秒后没按就取消
        } else {
            finish()
            System.exit(0)
        }
    }
}
